package cc.sjfx.sharedoc.services;

import java.util.ArrayList;
import java.util.List;

import com.bmob.BmobProFile;
import com.bmob.btp.callback.UploadBatchListener;

import cc.sjfx.sharedoc.R;
import cc.sjfx.sharedoc.activity.MainActivity;
import cc.sjfx.sharedoc.bean.FileInfo;
import cc.sjfx.sharedoc.bmob.BmobCache;
import cc.sjfx.sharedoc.bmob.FileInfo4Examination;
import cc.sjfx.sharedoc.bmob.UpdateStatus;
import cc.sjfx.sharedoc.db.bmob.Examination;
import cc.sjfx.sharedoc.db.bmob.User;
import cc.sjfx.sharedoc.utils.CheckUtils;
import cn.bmob.v3.listener.SaveListener;
import cn.mandroid.frame.toast.MLog;
import cn.mandroid.frame.utils.ThreadUtils;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

public class ReleaseService extends Service {
	Context context;
	NotificationManager nm;
	Notification notification;
	RemoteViews contentView;
	private PendingIntent pd;
	private int nid = 1234;
	private boolean released = false;
	private boolean finishUpload = false;
	int arg1, arg2, arg0;
	int lastFile = 0;
	int key;
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		context = this;
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification();
		notification.icon = R.drawable.ic_launcher;
		notification.tickerText = "发布中";
		notification.when = System.currentTimeMillis();
		notification.defaults = Notification.DEFAULT_LIGHTS;
		contentView = new RemoteViews(getPackageName(),
				R.layout.notification_release);
		notification.contentView = contentView;
		pd = PendingIntent.getActivity(this, 0, new Intent(this,
				MainActivity.class), 0);
		notification.setLatestEventInfo(this, "", "", pd);
		nm.notify(nid, notification);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		final Examination examination = (Examination) intent.getExtras()
				.getSerializable("examination");
		final FileInfo fileInfo = (FileInfo) intent.getExtras()
				.getSerializable("fileInfo");
		key=intent.getExtras().getInt("key",0);
		final List<FileInfo> infos = fileInfo.getFileInfos();
		final String[] path = new String[infos.size()];
		arg2 = path.length;
		for (int i = 0; i < path.length; i++) {
			path[i] = infos.get(i).getFilePath();
		}
		ThreadUtils.executorService.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				BmobProFile.getInstance(context).uploadBatch(path,
						new UploadBatchListener() {
							@Override
							public void onError(int arg0, String arg1) {
								// TODO Auto-generated method stub
								handler.sendEmptyMessage(4);
							}

							@Override
							public void onSuccess(boolean arg0, String[] arg1,
									String[] arg2) {
								// TODO Auto-generated method stub
								if (!CheckUtils.stringIsNull(arg1)) {
									List<FileInfo4Examination> list = new ArrayList<FileInfo4Examination>();
									for (int i = 0; i < arg1.length; i++) {
										FileInfo4Examination f = new FileInfo4Examination();
										f.setFileName(infos.get(i)
												.getFileName());
										MLog.i(i + ":" + arg1[i] + ":"
												+ arg2[i]);
										f.setFileNetName(arg1[i]);
										f.setFileNetUrl(arg2[i]);
										f.setFileSize(infos.get(i)
												.getFileSize());
										f.setFileType(infos.get(i)
												.getFileType());
										list.add(f);
									}
									examination.setFile(list);
									examination.setDate(System.currentTimeMillis()/1000);
									examination.save(context,
											new SaveListener() {
												@Override
												public void onSuccess() {
													// TODO Auto-generated
													// method stub
													released = true;
													handler.sendEmptyMessage(1);
												}

												@Override
												public void onFailure(int arg0,
														String arg1) {
													// TODO Auto-generated
													// method stub
													MLog.i("失败" + arg0 + arg1);
												}
											});
								}
							}

							@Override
							public void onProgress(int arg0, int arg1,
									int arg2, int arg3) {
								ReleaseService.this.arg0 = arg0;
								ReleaseService.this.arg1 = arg1;
								handler.sendEmptyMessage(2);
								if (lastFile != arg0) {
									lastFile = arg0;
									handler.sendEmptyMessage(3);
								}
								if (arg0 == arg2 && arg1 >= 99) {
									finishUpload = true;
									nm.cancel(nid);
									handler.sendEmptyMessage(1);
								}
							}
						});
			}
		});
		return super.onStartCommand(intent, flags, startId);
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 1:
				if (finishUpload && released) {
					Intent intent = new Intent();
					intent.setAction("releaseComplete");
					intent.putExtra("key",key);
					context.sendBroadcast(intent);
					nm.cancel(nid);
					BmobCache.updateUser(context, new UpdateStatus() {
						@Override
						public void onSuccess(User user) {
							// TODO Auto-generated method stub
							user.setPublishNum(user.getPublishNum() + 1);
							user.update(context);
						}
					});
					stopSelf();
				}
				break;
			case 2:
				MLog.i("get");
				contentView.setProgressBar(R.id.progressBar, 100, arg1, false);
				notification.contentView = contentView;
				nm.notify(nid, notification);
				Intent intent = new Intent();
				intent.setAction("releaseProgress");
				intent.putExtra("progress", arg1 / arg2
						+ ((arg0 - 1) * 100 / arg2));
				context.sendBroadcast(intent);
				break;
			case 3:
				contentView.setTextViewText(R.id.text, arg0 + "/" + arg2);
				break;
			case 4:
				Intent intent1 = new Intent();
				intent1.setAction("releaseFailed");
				context.sendBroadcast(intent1);
				stopSelf();
				break;
			default:
				break;
			}
		}
	};
}
